unit FTerrain;

interface
uses
	FOpenGl, FTextures, SysUtils, FFrustum, FBase, FFonts;

type
	TTerrain = array of array of array of integer;

	TTile = Record
		path : string;
		is_square : boolean;
	end;

var
	Terrain : TTerrain;

const
	TerrainSize = 80;
	TileSize = 128;
	TileFactor = 20;

procedure InitTerrain();
procedure DrawTerrain(terrain : TTerrain);

implementation


procedure InitTerrain();
var
	i, j : Integer;
begin
	SetLength(Terrain, TerrainSize);
	for i := 0 to TerrainSize - 1 do begin
		SetLength(Terrain[i], TerrainSize);
		for j := 0 to TerrainSize - 1 do begin
			SetLength(Terrain[i][j], 2);
			Randomize;
			Terrain[i][j][0] := Random(TileFactor + 3);
			if Terrain[i][j][0] <= TileFactor then
				Terrain[i][j][0] := 0
			else
				Terrain[i][j][0] := Terrain[i][j][0] - TileFactor;

			Terrain[i][j][1] := Random(4);
		end;
	end;
end;

procedure DrawTile(x : integer; y : integer; tile : TTile; ix : integer; iy : integer);
var
	max : integer;
begin	
	if tile.is_square then
		max := 4
	else
		max := 8;
	glEnable(GL_TEXTURE_2D);
	BindTexture(tile.path);

	glPushMatrix();
	glTranslatef(x * TileSize, y * TileSize, 0);

	glLoadName(glNameCount);
	Inc(glNameCount);
	glBegin(GL_QUADS);
		glTexCoord2f(ix/max, iy/4 + 1/4);
		glVertex3f(0,  TileSize, 0);

		glTexCoord2f(ix/max + 1/max, iy/4 + 1/4);
		glVertex3f( TileSize,  TileSize, 0);

		glTexCoord2f(ix/max + 1/max, iy/4);
		glVertex3f( TileSize, 0, 0);

		glTexCoord2f(ix/max, iy/4);
		glVertex3f(0, 0, 0);
	glEnd();

	glColor3f(0, 0, 0);
		glTranslatef(TileSize/2, TileSize/2, 0.1);
		glPrint(PChar(IntToStr(x) + ',' + IntToStr(y)), 40, false);
	glColor3f(1, 1, 1);

	glPopMatrix();

	glDisable(GL_TEXTURE_2D);
end;

procedure DrawTerrain(terrain : TTerrain);
var
	i: Integer;
	j: Integer;
	tile : TTile;
begin
	tile.path := 'Textures/Ashen_Grass.tga';
	tile.is_square := false;

	for i := 0 to TerrainSize - 1 do begin
		for j := 0 to TerrainSize - 1 do begin                           // Sqrt(2)/2
			if SphereInFrustum((i + 0.5) * TileSize, (j + 0.5) * TileSize, 0, 0.7071 * TileSize) then
				DrawTile(i, j, tile, terrain[i][j][0] + 4, terrain[i][j][1]);
		end;
	end;
	glLoadName(glNameCount);
	Inc(glNameCount);
end;
end.

